﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using Noria.Web.MyMSDN;
using Noria.Web.Utility;
using File = System.IO.File;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

namespace Noria.Web.Test
{
    [TestClass]
    public class GodaddyUploader
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private const string rootMM = @"D:\web\mymsdn\godaddy";
        private const string zipMM = @"D:\web\mymsdn\mm.zip";

        private const string ftpHost = "mymsdn.info";
        private const int ftpPort = 21;
        private const string ftpUid = "mymsdn";
        private const string ftpPwd = "User@123";

        private const string noriaUid = "stainboy";
        private const string noriaCode = "123456";


        [TestMethod]
        public void Packaging()
        {
            // 0. ftp
            FtpMM();
            log.Info("ftp uploaded.");

            // 1. zip file
            ZipMM();
            log.Info("zipped.");

            // 2. upload
            var mm = Upload();
            log.Info("uploaded.");

            // 3. extract
            Extract(mm);
            log.Info("extracted.");
        }

        [TestMethod]
        public void PackagingWithoutFtp()
        {
            // 0. ftp
            FakeFtpMM();
            log.Info("fake ftp uploaded.");

            // 1. zip file
            ZipMM();
            log.Info("zipped.");

            // 2. upload
            var mm = Upload();
            log.Info("uploaded.");

            // 3. extract
            Extract(mm);
            log.Info("extracted.");
        }

        private void FakeFtpMM()
        {
            foreach (var file in Directory.GetFiles(rootMM))
            {
                File.Delete(file);
                log.InfoFormat("file {0} deleted.", file);
            }
        }

        private void FtpMM()
        {
            var host = Dns.GetHostAddresses(ftpHost).First().ToString();
            log.Info("mymsdn.info -> " + host);

            foreach (var file in Directory.GetFiles(rootMM))
            {
                FtpTransfer(host, file);
                log.InfoFormat("file {0} tranfered.", file);
            }
            foreach (var file in Directory.GetFiles(rootMM))
            {
                File.Delete(file);
            }
        }

        private void FtpTransfer(string host, string file)
        {
            FtpClient ftp = new FtpClient(host, ftpUid, ftpPwd);
            ftp.Upload(new FileInfo(file).Name, file);
        }

        private string Upload()
        {
            string url = "http://api.mymsdn.info/upload.ashx?name=mm.zip";

            var req = WebRequest.CreateHttp(url);

            req.Method = WebRequestMethods.Http.Post;
            req.Headers.Add("NAuth", "Noria c3RhaW5ib3k6MTIzNDU2");

            var buffer = File.ReadAllBytes(zipMM);

            req.GetRequestStream().Write(buffer, 0, buffer.Length);
            var res = req.GetResponse();

            var length = res.ContentLength;
            var buffer2 = new byte[length];
            res.GetResponseStream().Read(buffer2, 0, buffer2.Length);

            dynamic obj = JObject.Parse(Encoding.UTF8.GetString(buffer2));
            string name = obj.name;

            return name;
        }

        private void ZipMM()
        {
            File.Delete(zipMM);
            ZipFile.CreateFromDirectory(rootMM, zipMM);
        }

        public void Extract(string file)
        {
            string url = "http://api.mymsdn.info/extract.ashx";

            var req = WebRequest.CreateHttp(url);

            req.Method = WebRequestMethods.Http.Post;
            req.Headers.Add("NAuth", "Noria c3RhaW5ib3k6MTIzNDU2");

            dynamic payload = new JObject();
            payload.name = file;
            payload.path = "/";
            var buffer = Encoding.UTF8.GetBytes(payload.ToString());

            req.GetRequestStream().Write(buffer, 0, buffer.Length);
            var res = req.GetResponse();
        }


        [TestMethod]
        public void ImportMethod()
        {
            string url = "http://api.mymsdn.info/import.ashx";

            var req = WebRequest.CreateHttp(url);

            
            req.Headers.Add("NAuth", "Noria c3RhaW5ib3k6MTIzNDU2");
            req.GetResponse().Dispose();

            //HttpBot.RequestNonQuery(null, "http://api.mymsdn.info/import.ashx");
            log.Info("extracted.");
        }
    }
}
